package com.dhcc.DRGsHosp.application.impl;

import java.util.List;
import java.util.Map;

import javax.inject.Named;

import org.dayatang.domain.EntityRepository;
import org.dayatang.domain.InstanceFactory;
import org.dayatang.querychannel.JdbcTemplateObj;
import org.dayatang.querychannel.QueryChannelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.transaction.annotation.Transactional;

import com.dhcc.DRGsHosp.application.DrgServiceGroupApplication;
import com.dhcc.DRGsHosp.core.domain.OtherGroupingResult;

/**
 * @title :DrgServiceGroupApplicationImpl.java
 * @description :DRGs分组服务
 * @author :LiQingYang
 * @date :2017年3月17日
 * @version :2.4.0
 * @copyright :DHCC 2013-2017
 */
@Named
@Transactional
public class DrgServiceGroupApplicationImpl implements DrgServiceGroupApplication {

	@Autowired
	private JdbcTemplateObj jdbcTemplateObj;
	
	private QueryChannelService queryChannel;

    private QueryChannelService getQueryChannelService(){
       if(queryChannel==null){
          queryChannel = InstanceFactory.getInstance(QueryChannelService.class,"queryChannel");
       }
     return queryChannel;
    }
    private EntityRepository getRepository() {
		EntityRepository repository = null;
		if (repository == null) {
			repository = InstanceFactory.getInstance(
					EntityRepository.class, "repository");
		}
		return repository;
	}
    
    /**
     *  @Description：获取数据总量
     *  @Author：liuhongjun 
     *  @see com.dhcc.DRGsHosp.application.DrgServiceGroupApplication#getMrCount(java.lang.String, java.lang.String, java.lang.String)
     */
	public List<Object[]> getMrCount(String dateFrom, String dateTo, String dateType){
		String sql = "select count(*) as totalCnt,sum(case when i.P00320000>60 then 1 else 0 end) GT60CN from drgs.mr_baseinfo bs left join drgs.mr_ipinfo i on bs.pmainindex=i.pmainindex WHERE 1=1 ";
			if("out_date".equals(dateType)) {
				sql+=" and to_char(i.P00290000,'yyyy-mm-dd') BETWEEN '"+dateFrom+"' AND '"+dateTo+"' ";
			}else if("push_date".equals(dateType)) {
				sql+=" and to_char(bs.push_date,'yyyy-mm-dd') BETWEEN '"+dateFrom+"' AND '"+dateTo+"' ";
			}
		List<Object[]> mrCountList = getQueryChannelService().createSqlQuery(sql).list();
		return mrCountList;
	
	}
	/**
	 *  @Description：获取组装的数据
	 *  @Author：liuhongjun 
	 *  @see com.dhcc.DRGsHosp.application.DrgServiceGroupApplication#findMrInfo(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public List<Map<String, Object>> findMrInfo(String param,String dateType) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select a.pmainindex case_id, a.P00090000 AGE, d.p00320000 ACCTUAL_DAYS, P00070001 GENDER, d.p00620001 sf0108,f.pd0101 DISEASE_CODE, \n ");
		sql.append(" d.p00800000 TOTAL_EXPENSE,  nvl(a.P00090001*30,0)+a.p00090002 sf0100, a.P00120000 sf0102,\n ");
		sql.append(" e.p90120201 sf0104, b.diags, c.opers, substr(cast(dbms_random.value as varchar2(10)),3,6) B_WT4_V1_ID \n ");
		sql.append(" from drgs.mr_baseinfo a\n ");
		sql.append(" left join drgs.mr_ipinfo d on a.pmainindex=d.pmainindex\n ");
		sql.append(" left join drgs.mr_appendpage e on a.pmainindex=e.pmainindex\n ");
		sql.append(" left join drgs.mr_diagnose f on a.pmainindex=f.pmainindex and f.pdtype='M'\n ");
		sql.append(" left join (\n ");
		sql.append(" select parid, wm_concat(diag_code) diags from(\n ");
		sql.append(" select pmainindex parid, a.pd0101 diag_code from drgs.mr_diagnose a \n ");
		sql.append(" where a.pdtype='O'\n ");
		sql.append(" )\n ");
		sql.append(" group by parid\n ");
		sql.append(" ) b on a.pmainindex=b.parid\n ");
		sql.append(" left join (\n ");
		sql.append(" select parid, wm_concat(oper_code) opers from(\n ");
		sql.append(" select pmainindex parid, a.po0101 oper_code \n ");
		sql.append(" from drgs.mr_operation a\n ");
		sql.append(" )\n ");
		sql.append(" group by parid\n ");
		sql.append(" ) c on a.pmainindex=c.parid\n ");
		if("out_date".equals(dateType)) {
			sql.append("  where  to_char(d.P00290000,'yyyy-mm-dd') BETWEEN '"+param+"' AND '"+param+"' ");
		}else if ("push_date".equals(dateType)) {
			sql.append("  where to_char(a.push_date,'yyyy-mm-dd') BETWEEN '"+param+"' AND '"+param+"' \n");
		}
		List<Map<String, Object>> mrList = jdbcTemplateObj.queryForList(sql.toString());
		return mrList;
	}
	
	/**
	 * 
	 *  @Description：获取对照 后的icd编码
	 *  @Author ZouYiyu  
	 *  @see com.dhcc.DRGsHosp.application.DrgServiceGroupApplication#getMatchResult(java.lang.String, java.lang.String)
	 */
	@Override
	@Cacheable(value = "drgscom3.1.1", key = "'DRGsGroupICDMatch' + #hICDCode +#icdDiaVerConfig +#icdOperVerConfig")
	public List<Object[]> getMatchResult(String hICDCode,String icdType,String icdDiaVerConfig,String icdOperVerConfig){
		String tableName="";
		String icdVersion="";
		if("O".equals(icdType)){
			tableName="DRGS.T_ICDMATCH_RESULT_OPER";
			icdVersion=icdOperVerConfig;
		}else{
			tableName="DRGS.T_ICDMATCH_RESULT_DIA";
			icdVersion=icdDiaVerConfig;
		}
    	String sql = " SELECT t.hosp_icd_code, t.hosp_icd_desc, t.bj_icd_code, t.bj_icd_desc  \n";
    	sql+=" FROM "+tableName+" t  WHERE ICDMAT_TYPE='1' AND t.hosp_icd_code= '"+hICDCode+"' and  t.drg_icd_version='"+icdVersion+"' ORDER BY LAST_UPDATE_DATE DESC ";
    	List<Object[]> resultList = getQueryChannelService().createSqlQuery(sql).list();
    	return resultList;
    }
	
	
	/**
	 * 
	 * @methodname    : getDRGsCountByVerCode
	 * @description   : 根据分组器版本编码获取字典表DRGs组数
	 * @param         : drgsVer:drg版本
	 * @author        : LiQingYang
	 * @return        :
	 * @date          : 2017年3月24日
	 */
	public int getDRGsCountByVerCode(String drgsVer){
		String sql = "SELECT COUNT(*)  FROM DRGS.T_DRGS T WHERE T.VER_CODE = '"+drgsVer+"'";
		int drgCount = Integer.parseInt(getQueryChannelService().createSqlQuery(sql).singleResult().toString());
		return drgCount;
	}
	
	@Override
	public List<String> findDiagCodeNameById(String parid) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select d.PD0101 diag from drgs.mr_diagnose d \n ");
		sql.append(" where d.PMAININDEX = '"+parid+"' and d.PDTYPE = 'O' \n ");
		sql.append(" order by d.PDINDEX asc\n ");
		List<String> resultList =  getQueryChannelService().createSqlQuery(sql.toString()).list();
		return resultList;
	}

	@Override
	public List<String> findOperCodeNameById(String parid) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select op.PO0101 oper from  \n ");
		sql.append(" drgs.mr_operation op where op.PMAININDEX = '"+parid+"' \n ");
		sql.append(" order by op.POTYPE ,op.POINDEX asc \n ");
		List<String> resultList = getQueryChannelService().createSqlQuery(sql.toString()).list();
		return resultList;
	}
	
	@Override
	public List<Object[]> listAdrgcount(String adrgcode) {
		StringBuilder sql = new StringBuilder();
		sql.append(" SELECT  adrg_code   FROM drgs.t_operation_adrg  WHERE  ADRG_CODE in ("+adrgcode+") \n ");
		List<Object[]> list = getQueryChannelService().createSqlQuery(sql.toString()).list();
		return list;
	}
	@Override
	public List<Object[]> getNoInGroupingLog(String dateFrom, String dateTo) {
		StringBuilder sql = new StringBuilder();
		sql.append(" select gl.mr_adm,drgver.ver_desc,pd.NOTIN_CODE,i.P00320000 ACCTUAL_DAYS,i.P00800000 TOTAL_EXPENSE,d.PD0101,gl.gl_j00,gl.gl_j01,gl.gl_j02,gl.gl_j03,gl.gl_j04,gl.gl_j05,gl.gl_j06,gl.gl_j07,gl.gl_j08,gl.gl_j08_1,gl.gl_j09, \n");
		sql.append(" gl.gl_j09_1,gl.gl_j10,gl.gl_j10_1,gl.gl_j10_2,gl.gl_j10_3,gl.gl_j10_4,gl.gl_j10_4_0,gl.gl_j10_5,gl.gl_j10_6,gl.gl_j11,  \n");
		sql.append(" gl.gl_j12,gl.gl_j13,gl.gl_j14,gl.gl_j15,gl.gl_j16,gl.gl_j17 \n");
		sql.append(" from drgs.t_patientdrg  pd left join  drgs.t_groupinglog gl on gl.mr_adm = pd.parid \n");
		sql.append(" left join drgs.mr_ipinfo i on i.pmainindex = gl.mr_adm \n");
		sql.append(" left join drgs.T_DRGVERSION drgver on pd.ver_code = drgver.ver_code \n");
		sql.append(" left join drgs.mr_diagnose d on i.pmainindex=d.pmainindex and d.pdtype='M' \n");
		sql.append(" where pd.pardrg_code is null and to_char(i.P00290000,'yyyy-mm-dd') between '"+dateFrom+"' and '"+dateTo+"' \n");
		List<Object[]> GroupingLogs = getQueryChannelService().createSqlQuery(sql.toString()).list();
		return GroupingLogs;
	}
	public List<Object[]> getOtherGroupResult(String pMainIndex) {
		String sql = "select error,ERROR_LOG,MDCS_MAIN from DRGS.T_OTHER_GROUPINGRESULT where MR_ID='"+pMainIndex+"' ";
		List<Object[]> resultList = getQueryChannelService().createSqlQuery(sql).list();
    	return resultList;
	}
	public int saveNotInReason(String pMainIndex,String notInReason) {
		String sql = "";
		sql += " BEGIN \n";
		sql +=      "UPDATE DRGS.T_PATIENTDRG SET NOTIN_REASON='"+notInReason+"' where PARID='"+pMainIndex+"'; \n";
		sql +=      "UPDATE DRGS.T_GROUPINGLOG SET NOTIN_REASON='"+notInReason+"' where MR_ADM='"+pMainIndex+"'; \n";
		sql += " 	END\n";
		sql += " COMMIT;";
		int i=getRepository().createSqlQuery(sql).executeUpdate();
		return i;
	}
	
	@Override
	public void creatOtherGroupingLog(OtherGroupingResult otherGroupingResult) {
		otherGroupingResult.save();
	}
}
